<template>
  <Panel>
    <!-- 标题 -->
    <template #tit>
      账号列表
    </template>
    <div>
      <!-- 1.表格 -->
      <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="account" label="账号" width="120">
        </el-table-column>
        <el-table-column prop="userGroup" label="用户组"> </el-table-column>
        <el-table-column prop="ctime" label="创建时间">
          <template v-slot="{ row }">
            {{ row.ctime | format }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <!-- 使用插槽显示按钮 -->
          <template v-slot="{ row }">
            <el-button type="primary" size="mini" @click="showItem(row)"
              >编辑</el-button
            >
            <el-button type="danger" size="mini" @click="delUser(row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 2分页的处理 -->
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
      <!-- 3按钮的操作 -->
      <div style="margin-top: 20px">
        <el-button type="danger" size="mini" @click="delAll"
          >批量删除</el-button
        >
        <el-button @click="toggleSelection()" type="primary" size="mini"
          >取消选择</el-button
        >
      </div>
      <!-- 4弹框 -->
      <el-dialog title="账号编辑" :visible.sync="dialogVisible" width="50%">
        <div>
          <!-- 这里写input框 -->
          <el-form
            :model="editForm"
            status-icon
            :rules="rules"
            ref="ruleForm"
            label-width="100px"
            class="demo-ruleForm"
            size="mini"
          >
            <el-form-item label="账号" prop="account">
              <el-input
                type="text"
                v-model="editForm.account"
                autocomplete="off"
              ></el-input>
            </el-form-item>

            <el-form-item label="用户组" prop="userGroup">
              <el-select v-model="editForm.userGroup" placeholder="请选择">
                <el-option label="普通管理员" value="普通管理员"> </el-option>
                <el-option label="超级管理员" value="超级管理员"> </el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <!-- 底部按钮 -->
        <span slot="footer" class="dialog-footer">
          <el-button size="mini" @click="dialogVisible = false"
            >取 消</el-button
          >
          <el-button size="mini" type="primary" @click="edituser('ruleForm')"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </div>
  </Panel>
</template>

<script>
//引入账号管理功能函数
import { accountList, delList, AllList, editList } from '../../api/users'
//引入moment时间插件
import moment from 'moment'

export default {
  data() {
    return {
      tableData: [],
      multipleSelection: [],
      currentPage: 1,
      //每页显示个数
      pageSize: 5,
      //总条数
      total: 0,
      dialogVisible: false,
      // 编辑用户的表单数据
      editForm: {
        account: '',
        userGroup: ''
      },
      //规则
      rules: {
        account: [{ required: true, message: '请输入账号', trigger: 'blur' }],
        userGroup: [
          { required: true, message: '请选择管理权限', trigger: 'change' }
        ]
      }
    }
  },
  // 数据创建后就调用
  created() {
    this.getUsers()
  },
  methods: {
    //渲染账号列表dom
    async getUsers() {
      const { data, total } = await accountList({
        currentPage: this.currentPage,
        pageSize: this.pageSize
      })
      this.tableData = data
      this.total = total
      // console.log(data)
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleSizeChange(val) {
      this.pageSize = val
      console.log(`每页 ${val} 条`)
      this.getUsers()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      console.log(`当前页: ${val}`)
      this.getUsers()
    },
    //删除单个
    delUser(id) {
      this.$confirm('此操作将永久删除该账号, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { code, msg } = await delList({ id })
          if (code === 0) {
            this.$message.success(msg)
            this.getUsers()
          }
          // console.log(data)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    //批量删除
    delAll() {
      //this.multipleSelection这个东西是一个数组,拿到里面的id,传给一个数组,当做发送请求所做的参数
      // console.log(this.multipleSelection, '批量删除')

      const ids = this.multipleSelection.map(item => item.id)
      if (ids.length === 0) return
      this.$confirm('此操作将永久删所选账号, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { code, msg } = await AllList({ ids: JSON.stringify(ids) })
          if (code === 0) {
            this.$message.success(msg)
            this.getUsers()
          }
          // console.log(data)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 点击弹框,并且渲染弹窗dom,
    showItem(row) {
      // account: '小汪'
      // ctime: '2021-07-07T12:57:59.000Z'
      // id: 85
      // imgUrl: 'default.jpg'
      // userGroup: '超级管理员'
      console.log(row, 'ROW')
      this.editForm = { ...row }
      this.dialogVisible = true
    },
    //发送请求,验证表格是否为空,更改账号列表的dom
    edituser(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          const { code, msg } = await editList({
            id: this.editForm.id,
            account: this.editForm.account,
            userGroup: this.editForm.userGroup
          })
          if (code === 0) {
            this.$message.success(msg)
            setTimeout(() => {
              this.dialogVisible = false
            }, 1500)
            this.getUsers()
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  },
  filters: {
    format(str) {
      return moment(str).format('YYYY-MM-DD  hh:mm:ss')
    }
  }
}
</script>

<style lang="less" scoped>
.el-input {
  width: 178px;
}
</style>
